import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/service/tuya_service.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/device/application/notification/device_pairnet.dart';
import 'package:casdon/modules/device/application/notification/product_category_notifier.dart';
import 'package:casdon/modules/device/domain/states/pair_state.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:tuya_home_sdk_flutter/tuya_home_sdk_flutter.dart';

enum DeviceSetupStep { authentication, networking, cloud, success }

final setupStepProvider = StateProvider.autoDispose<DeviceSetupStep>(
  (ref) => DeviceSetupStep.authentication,
);

@RoutePage()
class AddDeviceProgressScreen extends ConsumerStatefulWidget {
  final String deviceName;
  final String pid;
  final String ssid;
  final String pwd;
  final String? virtualId;

  const AddDeviceProgressScreen({
    super.key,
    required this.deviceName,
    required this.pid,
    required this.ssid,
    required this.pwd,
    required this.virtualId,
  });

  @override
  ConsumerState<AddDeviceProgressScreen> createState() =>
      _AddDeviceProgressScreenState();
}

class _AddDeviceProgressScreenState
    extends ConsumerState<AddDeviceProgressScreen>
    with TickerProviderStateMixin {
  late AnimationController _mainIconController;
  late AnimationController _stepIconController;
  late AnimationController _currentStepController;

  bool _pairListenerRegistered = false;
  bool _didHandleSuccess = false; // 防止 success 被处理多次

  @override
  void initState() {
    super.initState();

    // 主图标旋转控制器（2秒/圈）
    _mainIconController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..repeat();

    // 步骤图标旋转控制器（1秒/圈）
    _stepIconController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    )..repeat();

    // 当前步骤高亮动画控制器
    _currentStepController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
    );
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _startPairing();
      _currentStepController.forward();
    });
  }

  void _setupStateListener() {
    // 监听状态变化并执行相应操作
    if (!_pairListenerRegistered) {
      _pairListenerRegistered = true;
      ref.listen<DevicePairState>(devicePairingProvider, (previous, next) {
        // 回调不要直接在 build 阶段做 UI 改变，改用下一帧执行
        WidgetsBinding.instance.addPostFrameCallback((_) {
          Log.i('🔔 监听到配网状态变化: ${next.deviceModel}, ${next.state}');

          // 防止重复处理 success
          if (next.state == PairState.success &&
              previous?.state != PairState.success &&
              !_didHandleSuccess) {
            _didHandleSuccess = true;
            _simulateSetupProcess(next.deviceModel!); // 或者你要执行的 UI / 跳转
          } else if (next.state == PairState.failed &&
              previous?.state != PairState.failed) {
            if (mounted) _goPairNetFailedScreen();
          }
        });
      });
    }
  }

  Future<void> _startPairing() async {
    final service = ref.read(devicePairingProvider.notifier);
    await service.discoverAndPairDevice(
      targetPid: widget.pid,
      ssid: widget.ssid,
      password: widget.pwd,
    );
  }

  @override
  void dispose() {
    _mainIconController.dispose();
    _stepIconController.dispose();
    _currentStepController.dispose();
    super.dispose();
  }

  void _simulateSetupProcess(ThingSmartDeviceModel devModel) async {
    // 第一步：设备认证（立即开始动画）
    if (!mounted) return;
    ref.read(setupStepProvider.notifier).state = DeviceSetupStep.authentication;
    await Future.delayed(const Duration(seconds: 2));

    // 第二步：设备联网
    if (!mounted) return;
    ref.read(setupStepProvider.notifier).state = DeviceSetupStep.networking;
    await Future.delayed(const Duration(seconds: 1));

    // 第三步：设备入云
    if (!mounted) return;
    ref.read(setupStepProvider.notifier).state = DeviceSetupStep.cloud;
    await Future.delayed(const Duration(seconds: 2));

    // 第四步：设备成功
    if (!mounted) return;
    ref.read(setupStepProvider.notifier).state = DeviceSetupStep.success;
    await Future.delayed(const Duration(seconds: 1));

    // 跳转到成功页面
    if (!mounted) return;
    await _goPairNetSuccessScreen(devModel);
  }

  void _goPairNetFailedScreen() {
    context.router.push(
      PairnetFailedRoute(pid: widget.pid, deviceName: widget.deviceName),
    );
  }

  Future<void> _goPairNetSuccessScreen(ThingSmartDeviceModel devModel) async {
    if (!mounted) return;
    // nfc 配网
    if (widget.virtualId != null) {
      final bool deviceOnline = devModel.isOnline;
      try {
        await ref
            .read(deviceRepositoryProvider)
            .postNfcBind(
              deviceUuid: devModel.uuid,
              virtualId: widget.virtualId!,
            );
        ToastUtil.show("NFC标签绑定成功");
      } catch (e) {
        Log.e('⚡ NFC标签绑定失败', e, StackTrace.current);
        ToastUtil.show("NFC标签绑定失败");
      }
      // 绑定完成后，在线则进入面板，离线则调用接口获取用户设备nfc数据，打开产品说明页面
      if (!mounted) return;
      if (deviceOnline) {
        TuyaService().gotoPanel(
          deviceId: devModel.devId!,
          pid: devModel.productId,
          fromType: PanelFromType.nfc,
        );
      } else {
        await _openNfcReadme(devModel);
      }

      return;
    } else {
      if (!mounted) return;
      context.router.push(PairnetSuccessRoute(devId: devModel.devId!));
    }
  }

  Future<void> _openNfcReadme(ThingSmartDeviceModel devModel) async {
    final nfcReadMeMap = await ref
        .read(deviceRepositoryProvider)
        .getNFCProductReadMeInfo(
          deviceId: devModel.devId!,
          pid: devModel.productId,
        );
    if (!mounted) return;
    final dataWrapper = nfcReadMeMap["data"];
    if (dataWrapper is! Map<String, dynamic>) return;
    final data = dataWrapper["data"];
    if (data is! Map<String, dynamic>) return;
    final url = data["url"] as String?;
    final name = data["name"] as String?;
    if (url != null) {
      WebPageRoute(url: url, title: name ?? "").push(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    final currentStep = ref.watch(setupStepProvider);
    _setupStateListener();
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: CommonAppBar(title: "添加设备"),
      body: Padding(
        padding: const EdgeInsets.all(24.0),
        child: Column(
          children: [
            // 标题和提示
            Text(
              widget.deviceName.isEmpty
                  ? '正在添加设备'
                  : '正在添加【${widget.deviceName}】',
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Colors.black,
              ),
            ),
            const SizedBox(height: 8),
            const Text(
              '确保Wi-Fi信号良好',
              style: TextStyle(fontSize: 14, color: Colors.grey),
            ),
            const SizedBox(height: 40),

            Stack(
              alignment: Alignment.center,
              children: [
                RotationTransition(
                  turns: _mainIconController,
                  child: Image.asset(
                    Assets.images.pairNetIng.path,
                    width: 248.w,
                    height: 248.w,
                  ),
                ),

                Image.asset(
                  Assets.images.icNetRouter.path,
                  width: 84.w,
                  height: 84.w,
                ),
              ],
            ),
            const SizedBox(height: 40),

            // 步骤进度条
            _buildProgressSteps(currentStep),
          ],
        ),
      ),
    );
  }

  Widget _buildProgressSteps(DeviceSetupStep currentStep) {
    return SizedBox(
      height: 80, // 固定高度包含线和步骤内容
      child: Stack(
        children: [
          // 底部贯穿线
          Positioned(
            left: 34, // 左边距
            right: 34, // 右边距
            top: 23, // 调整到图标下方
            child: Container(
              height: 2,
              color: context.colorScheme.primary, // 基线颜色
            ),
          ),

          // 步骤内容
          Positioned.fill(
            child: Row(
              children: [
                Expanded(
                  child: _buildStepItem(
                    '设备认证',
                    isCompleted:
                        currentStep.index >
                        DeviceSetupStep.authentication.index,
                    isCurrent: currentStep == DeviceSetupStep.authentication,
                    // isFirst: true,
                  ),
                ),
                Expanded(
                  child: _buildStepItem(
                    '设备联网',
                    isCompleted:
                        currentStep.index > DeviceSetupStep.networking.index,
                    isCurrent: currentStep == DeviceSetupStep.networking,
                  ),
                ),
                Expanded(
                  child: _buildStepItem(
                    '设备入云',
                    isCompleted:
                        currentStep.index > DeviceSetupStep.cloud.index,
                    isCurrent: currentStep == DeviceSetupStep.cloud,
                  ),
                ),
                Expanded(
                  child: _buildStepItem(
                    '设备成功',
                    isCompleted: currentStep == DeviceSetupStep.success,
                    isCurrent: currentStep == DeviceSetupStep.success,
                    // isLast: true,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStepItem(
    String title, {
    required bool isCompleted,
    required bool isCurrent,
  }) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 12),
      child: Column(
        children: [
          // 步骤图标
          AnimatedContainer(
            duration: const Duration(milliseconds: 300),
            width: 24,
            height: 24,
            child: isCompleted
                ? Image.asset(
                    Assets.images.stepOk.path,
                    width: 24.w,
                    height: 24.w,
                  )
                : isCurrent
                ? RotationTransition(
                    turns: _stepIconController,
                    child: Image.asset(
                      Assets.images.stepIng.path,
                      width: 24.w,
                      height: 24.w,
                    ),
                  )
                : Image.asset(
                    Assets.images.stepIdle.path,
                    width: 24.w,
                    height: 24.w,
                  ),
          ),
          const SizedBox(width: 16),
          SizedBox(height: 5),
          // 步骤文本
          AnimatedDefaultTextStyle(
            duration: const Duration(milliseconds: 300),
            style: TextStyle(
              fontSize: 14,
              fontWeight: isCurrent ? FontWeight.w500 : FontWeight.normal,
              color: isCurrent
                  ? context.colorScheme.primary
                  : context.customColorThemeNonNull.textColor3,
            ),
            child: Text(title),
          ),
        ],
      ),
    );
  }
}
